import Vue from 'vue'
import confirmVue from './confirm.vue'

const PromptConstructor = Vue.extend(confirmVue)
const instance = new PromptConstructor({
  el: document.createElement('div')
})

PromptConstructor.prototype.closeConfirm = function () {
  const el = instance.$el
  el.parentNode && el.parentNode.removeChild(el)
  typeof this.callback === 'function' && this.callback()
}

const confirm = (options = {}) => {
  const isString = typeof options === 'string'
  instance.content = isString ? options : options.content
  instance.callback = options.callback

  document.body.appendChild(instance.$el)

  return new Promise((resolve, reject) => {
    instance.$on('closeConfirm', () => {
      resolve(false)
      instance.closeConfirm()
    })

    instance.$on('submit', (val) => {
      resolve(true)
      instance.closeConfirm()
    })
  })
}

export default confirm
